﻿using Autofac;
using Management.Infrastructure;
using Microsoft.EntityFrameworkCore;
using System.Reflection;
using Management.API.Filter;


namespace Management.API.Extensions
{
    public static class ServiceCollectionExtensions
    {
        /// <summary>
        /// 添加服务到服务容器
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <param name="configuration">配置对象</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection AddServices(this IServiceCollection services, IConfiguration configuration)
        {
            // 注册DbContext
            //   services.AddDbContext<ApplicationContext>(options =>
            //  options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

            services.AddDbContext<ApplicationContext>(options => options.UseMySql(configuration.GetConnectionString("DefaultConnection"),
              new MySqlServerVersion(new Version(5, 7, 0)))); // 使用 MySQL 5.7

            // 注入中介者
            services.AddMediatR(cfg => cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly()));

            // 注入AutoMapper
            services.AddAutoMapper(typeof(MapingProfile));
            

            // 注册仓储
            services.AddScoped(typeof(IBaseRepository<>), typeof(BaseRepository<>));

            //注入全局异常处理
            //services.AddControllers(x => x.Filters.Add<GlobalExceptionFilter>());

            return services;
        }



        /// <summary>
        /// 注册 Autofac 模块
        /// </summary>
        /// <param name="services">服务集合</param>
        /// <returns>服务集合</returns>
        public static IServiceCollection RegisterAutofac(this IServiceCollection services, ContainerBuilder containerBuilder)
        {
            containerBuilder.RegisterModule(new AutofacModuleRegister());
            return services;
        }
    }
}